package com.fish.gae.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fish.gae.entity.Comment;
import com.fish.gae.entity.PMF;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Controller
@RequestMapping(value = "/comment.htm")
public class CommentController {

	private static final Logger logger = Logger.getLogger(CommentController.class
			.getName());

	@RequestMapping(value = "/comment.htm",method = RequestMethod.POST)
	public String doPost(String content, Model model) {

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		String commentDate = sdf.format(new Date());
		model.addAttribute("content", content);
		Comment comment = new Comment(user, content, commentDate);

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(comment);

		} finally {
			pm.close();
		}
		return "comment";
	}
	
	
	@RequestMapping(value = "/comment.htm")
	@ModelAttribute("comments")
	public List<Comment> doGet(Model model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
//		if (user != null) {
//			response.setContentType("text/plain");
//			response.getWriter().println(
//					"Hello, " + user.getNickname());
//		} else {
//			response.sendRedirect(userService.createLoginURL(request.getRequestURI()));
//		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from  " + Comment.class.getName();
		List<Comment> comments = (List<Comment>) pm.newQuery(query).execute();
		if (comments.isEmpty()) {
			String message = "no message";
			System.out.print(message);
		} else {
			for (Comment co : comments) {
				if (co.getAuthor() == null) {
					String author = "man";
					System.out.println(author);
				} else {
					co.getAuthor().getNickname();
				}
				co.getContent();
			}
		}
		return comments;
	}

}
